package cn.yx.common.security.webmvc.handler;

import cn.yx.common.core.enums.CharsetEnum;
import cn.yx.common.core.enums.ContentTypeEnum;
import cn.yx.common.core.enums.ResponseCodeEnum;
import cn.yx.common.core.pojo.ResponseVo;
import cn.yx.common.core.util.json.jackson.JsonUtil;
import cn.yx.common.security.webmvc.sms.SmsCodeErrorException;
import cn.yx.common.security.webmvc.sms.SmsCodeExpirationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <p>用户认证失败处理器。
 * 用户认证失败，需要返回错误消息</p>
 *
 * @author Wgssmart
 */
@Component
@Slf4j
public class CustomAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException exception) throws IOException {
        String msg = ResponseCodeEnum.AUTHENTICATION_ERROR.getMessage();
        if (exception instanceof DisabledException) {
            msg = "cn.yx.common.security.userNotEnabled";
        } else if (exception instanceof UsernameNotFoundException) {
            msg = "cn.yx.common.security.userNotExist";
        } else if (exception instanceof BadCredentialsException) {
            msg = "cn.yx.common.security.badCredential";
        } else if (exception instanceof LockedException) {
            msg = "cn.yx.common.security.userLocked";
        } else if (exception instanceof SmsCodeExpirationException) {
            msg = exception.getMessage();
        } else if (exception instanceof SmsCodeErrorException) {
            msg = exception.getMessage();
        }
        log.error("authentication failure: {}, {}", exception.getMessage(), msg, exception);
        response.setContentType(ContentTypeEnum.JSON.getValue());
        response.setCharacterEncoding(CharsetEnum.UTF8.getValue());
        response.getWriter().write(JsonUtil.toJsonStr(ResponseVo.authenticationError(msg)));
    }
}
